#ifndef TLS_BVH_H
#define TLS_BVH_H

#include "geometry.h"
#include "linear_aggr.h"

namespace tls{

  struct bvh{
    linear_aggr mesh;

    struct node{
      int start,end;

      int axis;
      aabb box;

      node* right;
    };
    struct comp{
      int a;
      real m;
      comp(int axis,real mid):a(axis),m(mid){}
      bool operator()(const triangle& t)const{
	return t.tri.box.center()[a] < m;
      }
    };

    int n_nodes;
    node* nodes;

    bvh(const linear_aggr& aggr);
    ~bvh();

    //return the right most child of subtree at root if root is internal
    //otherwise return root itself
    node* build(node* root,int start,int end);

    bool intersect(ray& r, isect& hit)const;
    bool intersectP(ray& r)const;
  };

}//namespace tls

#endif

